package com.example.demo.Service.impl;

import com.example.demo.Common.Employee;
import com.example.demo.Context.BaseContext;
import com.example.demo.Exception.AccountNotFoundException;
import com.example.demo.Mapper.EmployeeMapper;
import com.example.demo.Proj.EmployeePageParam;
import com.example.demo.Proj.PageReslut;
import com.example.demo.Proj.PasswordEdit;
import com.example.demo.Proj.StatusConstant;
import com.example.demo.Service.EmployeeService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    EmployeeMapper employeeMapper;

    @Override
    public Employee getLogin(Employee e) {
        String username = e.getUsername();
        String password = e.getPassword();
        Employee login = employeeMapper.getLogin(username);
        if(login == null){
            throw new AccountNotFoundException("账号不存在");
        }
        if(!password.equals(login.getPassword())){
            throw new AccountNotFoundException("密码错误");
        }
        if(login.getStatus() == 0){
            throw new AccountNotFoundException("账号被锁定");
        }
        return login;
    }

    @Override
    public PageReslut getEmployeeList(EmployeePageParam employeePageParam) {
        PageHelper.startPage(employeePageParam.getPage(),employeePageParam.getPageSize());
        Page<Employee> page = employeeMapper.getEmployeeList(employeePageParam);
        return new PageReslut(page.getTotal(), page.getResult());
    }

    @Override
    public void addEmployee(Employee employee) {
        employee.setPassword("123456");
        employee.setStatus(StatusConstant.DISABLE);
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());
        log.info("employee insert: " + employee.toString());
        employeeMapper.insert(employee);
    }

    public Employee queryEmployeeById(Long id) {
        return employeeMapper.queryEmployeeById(id);
    }

    public void editEmployee(Employee employee) {
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);
    }

    @Override
    public void enableOrDisableEmployee(Long id, int status) {
        Employee employee = new Employee();
        employee.setId(id);
        employee.setStatus(status);
        employeeMapper.update(employee);
    }

    @Override
    public void editPassword(PasswordEdit passwordEdit) {
        passwordEdit.setId(BaseContext.getCurrentId());
        employeeMapper.editPassword(passwordEdit);
    }
}
